from sqlalchemy import Column, Integer, String, UniqueConstraint
from sqlalchemy.orm import relationship

from .base import BaseModel


class Cart(BaseModel):
    __tablename__ = "cart"
    __table_args__ = (
        UniqueConstraint(
            "user_id", "goods_id", "goods_sku_id", "is_delete",
            name="uk_user_goods_sku_status"
        ),
        {"comment": "用户购物车表"}
    )

    # 核心字段（与传入数据对应）
    id = Column(
        Integer,
        primary_key=True,
        autoincrement=True,
        comment="购物车记录ID"
    )
    user_id = Column(
        Integer,
        nullable=False,
        comment="关联用户ID"
    )
    goods_id = Column(
        Integer,
        nullable=False,
        comment="关联商品ID"
    )
    goods_sku_id = Column(
        String(50),
        default="",
        comment="商品SKU ID（区分商品规格）"
    )
    goods_num = Column(
        Integer,
        nullable=False,
        default=1,
        comment="商品数量（最小值1）"
    )
    store_id = Column(
        Integer,
        nullable=False,
        comment="关联店铺ID"
    )
    is_delete = Column(
        Integer,
        nullable=False,
        default=0,
        comment="是否删除（1=已删除，0=正常）"
    )

    # 关联关系：通过ORM可直接获取关联表的数据（按需配置）
    # 1. 关联用户：一个用户对应多个购物车记录
    user = relationship("User", backref="carts")  # User模型中可通过 user.carts 获取其购物车
    # 2. 关联商品：一个商品可在多个用户的购物车中
    goods = relationship("Goods", backref="carts")  # Goods模型中可通过 goods.carts 获取关联的购物车
    # 3. 关联店铺：一个店铺的商品可在多个用户的购物车中
    store = relationship("Store", backref="carts")  # Store模型中可通过 store.carts 获取关联的购物车
